package org.intellij.doctree;

import com.intellij.util.ui.Tree;
import org.intellij.doctree.node.DocTreeNode;
import org.intellij.doctree.node.DocumentNode;

import javax.swing.tree.TreeModel;
import javax.swing.tree.TreeNode;
import javax.swing.tree.TreePath;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

public class DocTree extends Tree {

    DocTreeNode currentNode;
    DocTreeNode nodeToRemove;
    DocTreeComponent docTreeComponent;

    public DocTree(DocTreeComponent docTreeComponent) {
        this.docTreeComponent = docTreeComponent;
        commonInit();
    }

    public DocTree(DocTreeComponent docTreeComponent, TreeModel treeModel) {
        super(treeModel);
        this.docTreeComponent = docTreeComponent;
        commonInit();
    }

    private void commonInit() {
        addMouseListener(new CurrentNodeListener());
        setCellRenderer(new DocTreeRenderer());
    }

    public String getToolTipText(MouseEvent evt) {
        if (getRowForLocation(evt.getX(), evt.getY()) == -1) return null;
        TreePath curPath = getPathForLocation(evt.getX(), evt.getY());
        TreeNode node = (TreeNode) curPath.getLastPathComponent();
        String toolTip = null;
        if (node instanceof DocTreeNode) {
            String url = null;
            String description = ((DocTreeNode) node).getDescription();
            if (node instanceof DocumentNode) {
                url = ((DocumentNode) node).getURL();
            }
            if (url == null || url.length() == 0) {
                if (description != null && description.length() > 0)
                    toolTip = "<html>" + description + "</html>";
            } else {
                if (description == null || description.length() == 0)
                    toolTip = "<html>" + url + "</html>";
                else
                    toolTip = "<html>" + url + "<br>" + description + "</html>";
            }

        }
        return toolTip;

    }

    public DocTreeNode getCurrentNode() {
        return currentNode;
    }

    public DocTreeComponent getDocTreeComponent() {
        return docTreeComponent;
    }

    public void setNodeToRemove(DocTreeNode node) {
        this.nodeToRemove = node;
    }

    public DocTreeNode getNodeToRemove() {
        return nodeToRemove;
    }

    private class CurrentNodeListener extends MouseAdapter {
        public void mouseClicked(MouseEvent e) {
            Point point = e.getPoint();
            TreePath path = getClosestPathForLocation(point.x, point.y);
            if (path != null)
                currentNode = ((DocTreeNode) path.getLastPathComponent());
            else
                currentNode = null;
        }
    }

}
